<?php
	if (isset($_GET['callback'])) {
		$cb = $_GET['callback'];
		
		// include db connect class
		require_once __DIR__ . '/db_connect.php';
		// connecting to db
		$db = new DB_CONNECT();
		
		$sql = 'SELECT id FROM question_list';
		$result = mysql_query($sql);
		$num_rows = mysql_num_rows($result);
		
		if ($num_rows == 0) {
		//no game found, make new game by creating question from question_bank insert to question_list
			makeSomeQuestions();
		}
		//found a game. surely the question_list table has at least one record that has 0 status
		$email = $_GET['email'];
		header("Location: gameplay.php?callback_redirect=$cb&email=$email");
		exit;
	}
	
	function makeSomeQuestions() {
		//ramdom 10 questions from question_bank
		//insert into question_list
		$result = mysql_query("SELECT id FROM question_bank");
		$num_row = mysql_num_rows($result);
		
		//array contains non duplicate numbers
		$non_dup_array = array();
		$non_dup_sql = "";
		
		for ($i = 0; $i < 10; $i++) {
			$rd_question_id = rand(0, $num_row-1);
			
			while (in_array($rd_question_id, $non_dup_array)) {
				$rd_question_id = rand(0, $num_row-1);
			}
			$non_dup_array[] = $rd_question_id;
			

			if ($i < 9) {
				$non_dup_sql .= $rd_question_id.",";
			} else {
				$non_dup_sql .= $rd_question_id;
			}

		}
		
		//non_dup_array has enough 10 question_ids, then take 10 questions from question_bank insert to question_list beyond 10 question_ids
		$result = mysql_query("SELECT * FROM question_bank WHERE ID IN (".$non_dup_sql.")");
		
		while ($data_row = mysql_fetch_array($result)) {
			//insert a new row data with default status - 0 - non anyone truely answer this question.
			$sql = "INSERT INTO question_list(id, question, answer_list, expected_answer, status) VALUES($data_row[0], '$data_row[1]', '$data_row[2]', '$data_row[3]', 0)";
			mysql_query($sql);
		};
	}
?>